#include "ListNode.h"
#include <vector>
using namespace std;

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        vector<ListNode*> two = split(head);
        ListNode* l1 = sortInList(two[0]);
        ListNode* l2 = sortInList(two[1]);
        return merge(l1, l2);
    }

    vector<ListNode*> split(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = nullptr;
        vector<ListNode*> ret;
        ret.push_back(head);
        ret.push_back(slow);
        return ret;
    }

    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode* new_head = new ListNode(-1);
        ListNode* p = new_head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                p->next = l1;
                l1 = l1->next;
            } else {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if (l1) {
            p->next = l1;
        }
        if (l2) {
            p->next = l2;
        }
        return new_head->next;
    }
};